<template>
  <view class="w-full max-w-[750rpx] min-h-screen bg-[#f5f7fa] mx-auto flex flex-col">
    <!-- 头部标题 -->
    <view class="bg-[#2196F3] sticky top-0 z-10 text-white px-[32rpx] py-[24rpx] rounded-b-[32rpx]">
      <text class="text-[36rpx] font-semibold">消息</text>
    </view>
    
    <!-- 系统信息提示 -->
    <view class="mx-[24rpx] mt-[24rpx]">
      <view 
        class="bg-white rounded-[24rpx] w-full p-[24rpx] box-border shadow-sm flex items-center cursor-pointer"
        @click="goToSystemMessages"
      >
        <view class="flex flex-1 mr-2 items-center min-w-0">
          <view class="w-[80rpx] h-[80rpx] rounded-full bg-[#e3f2fd] text-[#2196F3] flex items-center justify-center font-bold text-[32rpx] mr-[20rpx] flex-shrink-0">
            系
          </view>
          <view class="flex-1 min-w-0">
            <view class="text-[30rpx] font-bold text-[#222] mb-[8rpx]">系统消息</view>
            <view class="text-[24rpx] text-[#666] truncate">{{ latestSystemMessage }}</view>
          </view>
        </view>
        <view class="flex items-center flex-shrink-0">
          <view v-if="systemUnreadCount > 0" class="bg-red-500 text-white text-[20rpx] px-[8rpx] py-[2rpx] rounded-[12rpx] mr-[12rpx]">
            {{ systemUnreadCount }}
          </view>
          <IconFont name="right" size="20" class="text-[#999]" />
        </view>
      </view>
    </view>
    
    <!-- 聊天用户列表 -->
    <view class="mx-[24rpx] mt-[24rpx] mb-[80rpx] flex-1">
      <view v-if="loading" class="flex justify-center items-center h-[200rpx]">
        <view class="text-[28rpx] text-[#999]">加载中...</view>
      </view>
      
      <view v-else-if="chatUsers.length === 0" class="bg-white rounded-[24rpx] p-[80rpx] text-center">
        <view class="text-[28rpx] text-[#999] mb-[16rpx]">暂无聊天记录</view>
        <view class="text-[24rpx] text-[#ccc]">开始与用户聊天吧</view>
      </view>
      
      <view v-else class="space-y-[16rpx]">
        <view
          v-for="(user, index) in chatUsers"
          :key="user.id"
          class="bg-white rounded-[24rpx] p-[24rpx] shadow-sm flex items-center cursor-pointer relative"
          @click="goToChat(user)"
        >
          <image
            :src="getFullPath(user.avatar)"
            class="w-[80rpx] h-[80rpx] rounded-full mr-[20rpx] object-cover"
            @error="handleImageError"
            mode="aspectFill"
          />
          <view v-if="user.dot" class="absolute top-[24rpx] left-[84rpx] w-[24rpx] h-[24rpx] rounded-full bg-red-500"></view>
          <view class="flex-1">
            <view class="flex items-center justify-between mb-[8rpx]">
              <text class="text-[30rpx] font-bold text-[#222] truncate flex-1 mr-[12rpx]">{{ user.name }}</text>
              <text class="text-[22rpx] text-[#999] flex-shrink-0">{{ user.lastTime }}</text>
            </view>
            <view class="flex items-center justify-between">
              <text class="text-[26rpx] text-[#666] truncate flex-1 mr-[12rpx] max-w-[400rpx]">{{ user.lastMessage }}</text>
              <view v-if="user.unreadCount > 0" class="bg-red-500 text-white text-[20rpx] px-[8rpx] py-[2rpx] rounded-[12rpx] min-w-[32rpx] text-center flex-shrink-0">
                {{ user.unreadCount > 99 ? '99+' : user.unreadCount }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { getFullPath, post } from "@/utils/request";
import { useUserStore } from '@/store/user';
import ren from '@/assets/pic/ren.png'
import { onChangeTab } from "@/utils/hack";
const userStore = useUserStore();

Taro.useDidShow(() => {
  onChangeTab('message')
})

/**
 * 消息列表页面
 * @description 显示系统消息提示和聊天用户列表
 * @performance 分页加载，虚拟滚动优化
 */

const loading = ref(true)
// const systemUnreadCount = ref(3)
const latestSystemMessage = ref('')

// 聊天用户列表
const chatUsers = ref([
  {
    id: '1',
    name: '张小美',
    avatar: 'http://www.dzgktf.com/templets/default/images/wtyt.jpg',
    lastMessage: '好的，我会按时到岗的，请放心，我一定会准时到达工作地点，并且会认真完成所有分配给我的工作任务',
    lastTime: '14:30',
    unreadCount: 2
  }
])

const handleImageError = (e: any) => {
  console.log('e==>', e)
  e.target.src = ren
}


/**
 * 跳转到系统消息列表
 */
const goToSystemMessages = () => {
  Taro.navigateTo({
    url: '/pages/message/system-messages'
  })
}

/**
 * 跳转到聊天页面
 */
const goToChat = (user: any) => {
  console.log('user==>', user)
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${user.id}&userName=${user.name}`
  })

  // Taro.navigateTo({
  //   url: `/pages/message/webs?other=${user.id}`
  // })
}

onMounted(() => {
  // 模拟加载
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 信息列表
const getSysMessageList = async () => {
  const res = await post('/message/list')
  console.log('信息列表==>',res)
  let list: any[] = []
  res.data.forEach((item: any) => {
    let obj:any = {};
    console.log(item.columns.from_user + "->" + item.columns.to_user)
    if(item.columns.from_user == userStore.userInfo.id){
      obj = {
        id: item.columns.to_user,
        name: item.columns.to_user_name,
        avatar: item.columns.to_avatar_url || ren,
        lastMessage: item.columns.content,
        lastTime: item.columns.create_time
      }
    }
    else{
      obj = {
        id: item.columns.from_user,
        name: item.columns.from_user_name,
        avatar: item.columns.from_avatar_url || ren,
        lastMessage: item.columns.content,
        lastTime: item.columns.create_time,
        dot: item.columns.status == 0
      }
    }
    if(!list.find((item: any) => item.id == obj.id)){
      list.push(obj)
    }
    
  })
 

  chatUsers.value = list;
  console.log('chatUsers.value==>', chatUsers.value)
  // if(res.code == 0) {

  // }
}
const systemUnreadCount = ref(0)
// 最新消息
const getSysMessageNewest = async () => {
  const res = await post('/sysMessage/newest')
  console.log('最新消息==>',res)
  if(res.code == 0){
    latestSystemMessage.value = res.data.columns.title;
    systemUnreadCount.value = res.data.columns.unread || 0;
  }
}

Taro.useDidShow(() => {
  getSysMessageList()
  getSysMessageNewest()
  Taro.hideTabBarRedDot({
    index: 3
  })
})

onMounted(() => {
  // getSysMessageList()
  // getSysMessageNewest()
  setTimeout(() => {
    loading.value = false
  }, 500)
})

</script>